package core;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.BitmapCache;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
 * RequestQueue的管理器
 *
 * @Warning 不要直接持有 RequestQueue 的引用
 */
public final class DataRequester {

    static final String PRIVATE_DOMAIN = "121.43.67.8";
    static final int RETRY_COUNT = 2;

    static RequestQueue requestQueue;
    static ImageLoader imageLoader;

    public static RetryPolicy getRetryPolicy() {
        return new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, RETRY_COUNT, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    }

    public static void enableDebug(boolean enable) {
        VolleyLog.DEBUG = enable;
    }

    /**
     * 网络请求队列单例
     */
    public static RequestQueue getInstance(Context context) {
        if (requestQueue == null) {
            synchronized (DataRequester.class) {
                if (requestQueue == null) {
                    requestQueue = Volley.newRequestQueue(context.getApplicationContext());
                }
            }
        }
        return requestQueue;
    }

    /**
     * 网络图片请求单例
     */
    public static ImageLoader getImageLoader(Context context) {
        if (imageLoader == null) {
            synchronized (DataRequester.class) {
                if (imageLoader == null) {
                    imageLoader = new ImageLoader(getInstance(context), new BitmapCache());
                }
            }
        }
        return imageLoader;
    }

    public static void stop() {
        if (requestQueue != null) {
            requestQueue.stop();
            requestQueue = null;
            imageLoader = null;
        }
    }
}
